package web.controllers;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import map.beans.EmpResponseBean;
import map.beans.JqgridResponse;
import map.beans.MapEngineRegistrationBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import web.service.interfaces.EngineRegistrationServiceInterface;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;


@Controller
@RequestMapping(value = "/admin/map/engine")
public class MapEngineRegistrationController {
	private static Logger LOGGER = LoggerFactory.getLogger(MapEngineRegistrationController.class);

	@Autowired
	private EngineRegistrationServiceInterface mapEngineRegistrationService;
	
	public MapEngineRegistrationController() { }

	
	@SuppressWarnings("unused")
	@RequestMapping(value = "/records", method = RequestMethod.GET)
	@ResponseBody
	public JqgridResponse<MapEngineRegistrationBean> records(@Context HttpServletRequest request, @RequestParam("_search") Boolean search,
			@RequestParam(value = "nd", required = false) String filters,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord) {		
	
		JqgridResponse<MapEngineRegistrationBean> response = null;
		Pageable pageRequest = new PageRequest(page - 1, rows);

		try {
			if (sord != null) {
				Sort sort = null;
				sort = new Sort((sord.equals("asc") ? Direction.ASC : Direction.DESC), sidx);
				pageRequest = new PageRequest(page - 1, rows, sort);

			} else {
				pageRequest = new PageRequest(page - 1, rows);
			}						

			mapEngineRegistrationService.setServerInfo(request);
			List<MapEngineRegistrationBean> mapEnginesDtos = mapEngineRegistrationService.findAll();			

			response = new JqgridResponse<MapEngineRegistrationBean>();
			response.setRows(mapEnginesDtos);
			response.setRecords(Integer.valueOf(mapEnginesDtos.size()).toString());
			response.setTotal(Integer.valueOf(1).toString());
			response.setPage(Integer.valueOf(1).toString());

		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		}

		return response;
	}

	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public EmpResponseBean registerMapEngine(@Valid @ModelAttribute(value = "mapEngine") MapEngineRegistrationBean mapEngine, BindingResult result) {
		
		EmpResponseBean response = new EmpResponseBean();
		
		ValidationUtils.rejectIfEmpty(result, "name", "Manifest Name can NOT be null");
		ValidationUtils.rejectIfEmpty(result, "url",  "Manifest URL can NOT be null");
						
		if ( !result.hasErrors() ) {
			mapEngineRegistrationService.register(mapEngine);

			response.setStatus("SUCCESS");
			response.setResult(mapEngine);
		} else {
			response.setStatus("FAIL");
			response.setResult(result.getAllErrors());
		}

		return response;
	}
	
	@RequestMapping(value = "/inline/update", method = RequestMethod.POST)
	@ResponseBody 
	public EmpResponseBean inlineUpdateMapEngineRegistration(
			@RequestParam(value = "reload", required = false, defaultValue = "false") boolean reload,
			@RequestParam(value = "id",     required = true,  defaultValue = "") Long id,
			@RequestParam(value = "name",   required = true,  defaultValue = "") String name,
			@RequestParam(value = "url",    required = true,  defaultValue = "") String url) {
		
		MapEngineRegistrationBean mapEngine = mapEngineRegistrationService.getMapEngine(id);
		mapEngine.setName(name);
		mapEngine.setUrl(url);
		
		List<MapEngineRegistrationBean> mapEnginesDto = new ArrayList<MapEngineRegistrationBean>();
		EmpResponseBean response = new EmpResponseBean();

		mapEngineRegistrationService.update(mapEngine);

		mapEnginesDto.add(mapEngine);
		response.setStatus("SUCCESS");
		response.setResult(mapEnginesDto);

		return response;
	}


	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody 
	public EmpResponseBean updateMapEngineRegistration(@RequestParam(value="reload", required=false, defaultValue="false") boolean reload, 
			@Valid @ModelAttribute(value = "mapEngine") MapEngineRegistrationBean mapEngine, BindingResult result ) {
		
		List<MapEngineRegistrationBean> mapEnginesDto = new ArrayList<MapEngineRegistrationBean>();
		EmpResponseBean response = new EmpResponseBean();
		
		ValidationUtils.rejectIfEmpty(result, "name", "Manifest Name can not be null");
		ValidationUtils.rejectIfEmpty(result, "url",  "Manifest URL can not be null");				
		
		if ( !result.hasErrors() ) {
			mapEngineRegistrationService.update(mapEngine);

			mapEnginesDto.add(mapEngine);
			response.setStatus("SUCCESS");
			response.setResult(mapEnginesDto);
		} else {
			response.setStatus("FAIL");
			response.setResult(result.getAllErrors());
		}

		return response;
	}

	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public EmpResponseBean delete(@RequestParam Long... ids) {
		MapEngineRegistrationBean mapEngineDto = null;
		Boolean result = false;
		try {
			for (long curId : ids) {
				mapEngineDto = new MapEngineRegistrationBean();
				mapEngineDto.setId(curId);
				result = mapEngineRegistrationService.delete(mapEngineDto);
			}
		} catch (Exception e) {
			LOGGER.error("Delete operation on " + mapEngineDto.getId() + " not successful");
		}
		
		EmpResponseBean resp = new EmpResponseBean();
		resp.setResult(result);
		
		return resp;
	}

	
	@RequestMapping(value = "/gridLoader", method = RequestMethod.GET)
	@ResponseBody
	public void getData(@Context HttpServletResponse response) {
		try {
			response.setContentType("text/html");
			response.setStatus(HttpServletResponse.SC_OK);			
			
			response.getOutputStream().println(HttpServletResponse.SC_OK);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value="/settings/save/{properties}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
	@ResponseBody
	public String addApplicationSettings(@RequestBody String record, @RequestParam String properties) {		
		if (record == null) {
			System.out.println("NULL");
		}

		MapEngineRegistrationBean mapEngine = new MapEngineRegistrationBean();
		try {
			System.out.println(record + "\n\n");
			Gson gson = new Gson();			

			Type mapType = new TypeToken<Map<String,String>>(){private static final long serialVersionUID = -8874248689717486194L;}.getType();
			Type merType = new TypeToken<MapEngineRegistrationBean>(){private static final long serialVersionUID = -8874248689717486194L;}.getType();
			
			Map<String, String> propertiesMap = gson.fromJson(properties, mapType);
			
			mapEngine = gson.fromJson(record, merType);	
			mapEngine.setProperties(propertiesMap);

			mapEngineRegistrationService.update(mapEngine);
			
		} catch (Exception e) {
			LOGGER.warn(e.getMessage());
		}
		
		return properties;
	}
	
	
	@RequestMapping(value="/settings/retrieve/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
	@ResponseBody
	public String getApplicationSettings(@RequestParam Long id) {		
		MapEngineRegistrationBean mapEngine = mapEngineRegistrationService.getMapEngine(id);
		Gson gson = new Gson();
		String json = "";
		
		try {	
			Type mapType = new TypeToken<Map<String,String>>(){private static final long serialVersionUID = -8874248689717486194L;}.getType();
			
			if (mapEngine.getProperties().isEmpty()) {
				mapEngineRegistrationService.update(mapEngine);
			}
			
			json = gson.toJson(mapEngine.getProperties(), mapType);					
			
		} catch (Exception e) {
			LOGGER.warn(e.getMessage());
		}
		
		return json;
	}	

	@RequestMapping(value="/msgs/{msg}", method = RequestMethod.GET)
	@ResponseBody
	public String getMessage(HttpServletRequest request, @PathVariable String msg) {
		System.out.println(msg + "\n\n");
		
		return msg;
	}
}
